package com.baizw.cultivation.util;

import cn.hutool.extra.spring.SpringUtil;
import com.alibaba.druid.pool.DruidDataSource;
import com.baizw.cultivation.module.admin.entity.AutoGeneratorEntity;
import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

/**
 * 自动生成工具类
 *
 * @author 剧终1204
 * @version V1.0
 * @date 2020年05月28日 10:55
 */
@Slf4j
@Component
public class GeneratorUtil {

    private static Environment environment;

    @Autowired
    public void setEnvironment(Environment environment) {
        GeneratorUtil.environment = environment;
    }

    /**
     * 初始化数据源配置
     * <p>
     * 默认开启使用本项目数据库
     * <p/>
     *
     * @param entity 自定义配置实体
     * @return DataSourceConfig
     */
    public static DataSourceConfig initDataSourceConfig(AutoGeneratorEntity entity) {
        DataSourceConfig sourceConfig = new DataSourceConfig();
        if (entity.isUseProjectDatabase()) {
            DruidDataSource dataSource = SpringUtil.getBean(DruidDataSource.class);
            String driverClassName = dataSource.getDriverClassName();
            String loginName = dataSource.getUsername();
            String password = dataSource.getPassword();
            String url = dataSource.getUrl();

            sourceConfig.setDriverName(driverClassName);
            sourceConfig.setUrl(url);
            sourceConfig.setUsername(loginName);
            sourceConfig.setPassword(password);
            return sourceConfig;
        }
        sourceConfig.setDriverName(entity.getDriverName());
        sourceConfig.setUrl(entity.getUrl());
        sourceConfig.setUsername(entity.getLoginName());
        sourceConfig.setPassword(entity.getPassword());
        return sourceConfig;
    }
}
